package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jmx.export.naming.IdentityNamingStrategy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Transactional
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        //清理当前菜品分类下的缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        dishService.saveDishAndFlavors(dishDto);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Dish> pageInfo =new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> lqw =new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,lqw);
        Page<DishDto> result =new Page<>(page,pageSize);
        BeanUtils.copyProperties(pageInfo,result,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> resultList=new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            Long id = record.getCategoryId();
            Category category = categoryService.getById(id);
            String categoryName = category.getName();
            if (categoryName!=null){
                dishDto.setCategoryName(categoryName);
            }
            resultList.add(dishDto);
        }
        result.setRecords(resultList);
        return R.success(result);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //清理当前菜品分类下的缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    /**
     * 查询菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> collect=null;
        //动态构造key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //从redis中获取缓存数据
        collect = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (collect!=null){
            //如果存在直接返回,无需查询数据库
            return R.success(collect);
        }
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);

        collect = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> ddlqw = new LambdaQueryWrapper<>();
            ddlqw.eq(DishFlavor::getDishId, id);
            List<DishFlavor> dishFlavors = dishFlavorService.list(ddlqw);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
         redisTemplate.opsForValue().set(key,collect, Duration.ofMinutes(60));
        //Dish dish = dishService.getById(categoryId);
        return R.success(collect);
    }

    /**
     * 批量删除
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.delete(ids);

        return R.success("删除成功");
    }

    @PostMapping("/status/0")
    public R<String> update(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,ids);
        List<Dish> list = dishService.list(lqw);
        for (Dish dish : list) {
            if (dish.getStatus()==1){
                dish.setStatus(0);
            }else{
                dish.setStatus(1);
            }
        }
        dishService.updateBatchById(list);
        return R.success("修改成功");
    }

    @PostMapping("/status/1")
    public R<String> updateStatus(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,ids);
        List<Dish> list = dishService.list(lqw);
        for (Dish dish : list) {
            if (dish.getStatus()==1){
                dish.setStatus(0);
            }else{
                dish.setStatus(1);
            }
        }
        dishService.updateBatchById(list);
        return R.success("修改成功");
    }

}
